package project.base.common.config

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.cache.annotation.CachingConfigurerSupport
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.serializer.StringRedisSerializer
import org.springframework.data.redis.serializer.RedisSerializer

/**
 * redis配置
 * @author 三味
 * @since 2022/3/3 15:23
 */
@Suppress("SpringJavaInjectionPointsAutowiringInspection")
@Configuration
open class RedisConfig : CachingConfigurerSupport() {

    /**
     * 注入 RedisConnectionFactory
     */
    @Autowired
    lateinit var redisConnectionFactory: RedisConnectionFactory

    /**
     * 配置redisTemplate
     *
     * 通过redisConnectionFactory引入redis在配置文件中的连接配置
     */
    @Bean
    open fun redisTemplate(): RedisTemplate<*, *> {
        val redisTemplate: RedisTemplate<*, *> = StringRedisTemplate(redisConnectionFactory)
        val stringRedisSerializer: RedisSerializer<*> = StringRedisSerializer()
        redisTemplate.valueSerializer = stringRedisSerializer
        redisTemplate.keySerializer = stringRedisSerializer
        redisTemplate.hashKeySerializer = stringRedisSerializer
        redisTemplate.hashValueSerializer = stringRedisSerializer
        redisTemplate.afterPropertiesSet()
        return redisTemplate
    }
}
